package com.superheroes.exception;
import com.superheroes.utils.result.NotSayUncle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * @author chb
 * 全局异常捕获处理
 * @date 2020/4/21 15:38
 */
@ControllerAdvice
public class ExceptionUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionUtils.class);




    /**
     * 所有验证框架异常捕获处理
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    public Object validationExceptionHandler(Exception exception) {
        BindingResult bindResult = null;
        if (exception instanceof BindException) {
            bindResult = ((BindException) exception).getBindingResult();
        } else if (exception instanceof MethodArgumentNotValidException) {
            bindResult = ((MethodArgumentNotValidException) exception).getBindingResult();
        }
        String msg;
        if (bindResult != null && bindResult.hasErrors()) {
            msg = bindResult.getAllErrors().get(0).getDefaultMessage();
            if (msg.contains("NumberFormatException")) {
                msg = "参数类型错误！";
            }
        }else {
            msg = "系统繁忙，请稍后重试...";
        }
        return NotSayUncle.err(msg);
    }

    /**
     * 业务异常
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Object allBusinessExceptionHandler(MyException exception) {
        return NotSayUncle.err(exception.getMessage());
    }


    /**
     * 未知的异常捕获处理
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Object allUnknowExceptionHandler(HttpServletRequest request, Exception exception) {
        String error = logError(request, exception);
        //可以发送邮件通知开发
        return NotSayUncle.err("系统繁忙，请稍后重试!");
    }

    private String logError(HttpServletRequest request, Exception exception) {
        LOGGER.error("发生未知异常:", exception);
        StringWriter sw = new StringWriter();
        sw.append(String.format("Date:{%s};\n", new Date()));
        sw.append(String.format("url:{%s}产生错误;\n", request.getRequestURI()));
        sw.append(String.format("请求IP:{%s};\n", request.getRemoteAddr()));
        sw.append(String.format("type:{%s};\n", request.getMethod()));
        sw.append(String.format("请求参数:{%s};\n",  request.getParameterMap()));
        exception.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }


//    @ExceptionHandler(Exception.class)
//    @ResponseBody
//    public  NotSayUncle exceptionHandler(Exception e){
//        LOGGER.error("全局异常处理捕获异常",e);
//        return NotSayUncle.err("系统异常");
//    }
//
//

}
